package com.bdqn.bookshop.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bdqn.bookshop.common.BookConstants;
import com.bdqn.bookshop.common.BookStateEnum;
import com.bdqn.bookshop.dao.BooksMapper;
import com.bdqn.bookshop.entity.Books;
import com.bdqn.bookshop.entity.MallUser;
import com.bdqn.bookshop.service.BooksService;
import com.bdqn.bookshop.utils.DataGridViewResult;
import com.bdqn.bookshop.utils.FileResult;
import com.bdqn.bookshop.utils.FileUtil;
import com.bdqn.bookshop.utils.Result;
import com.bdqn.bookshop.vo.BooksVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;


import javax.servlet.http.HttpServletRequest;
import java.awt.print.Book;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @author : 罗若然[LUO_RUO_RAN]
 * @date : 2020-07-24 15:59
 **/
@Service
@Transactional
public class BooksServiceImpl extends ServiceImpl<BooksMapper, Books> implements BooksService {
    @Override
    public DataGridViewResult booksList(BooksVo booksVo) {
        IPage<Books> page = new Page<>();
        QueryWrapper<Books> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(booksVo.getBookName()),"book_name",booksVo.getBookName());
        queryWrapper.eq(booksVo.getIsdiscount()!=null,"isdiscount",booksVo.getIsdiscount());
        queryWrapper.eq(booksVo.getState()!=null,"state",booksVo.getState());
        queryWrapper.like(StringUtils.isNotBlank(booksVo.getClassifyId()),"classify_id",booksVo.getClassifyId());
        queryWrapper.ge(booksVo.getStartTime()!=null,"create_time",booksVo.getStartTime());
        queryWrapper.le(booksVo.getEndTime()!=null,"create_time",booksVo.getEndTime());
        baseMapper.selectPage(page,queryWrapper);
        return new DataGridViewResult(page.getTotal(),page.getRecords());
    }


    @Override
    public Result selectById(Integer id) {

        Books books = baseMapper.selectBookById(id);
        if (books!=null){
            books.setPac(baseMapper.selectParentAndChildByBookClassify(books.getClassifyId()));
            return Result.createSuccess(books,"成功");
        }
        return Result.createError("抱歉没有查询到数据");
    }

    @Override
    public Result editBooks(MultipartFile file, Books books, HttpServletRequest request) {
        if (file!=null){
            if(books.getId()!=null){
                String fileName = books.getImageUrl().substring(books.getImageUrl().lastIndexOf('/')+1);
                FileUtil.deleteFile(request,fileName,BookConstants.BOOKS_SAVE_PATH);
            }
            String newFileName = UUID.randomUUID().toString().replace("-", "").toUpperCase();
            FileResult fr = FileUtil.saveFileToPath(request,file, BookConstants.BOOKS_SAVE_PATH,BookConstants.BOOKS_MAPPING_URL,newFileName);
            if (fr!=null){
                books.setImageUrl(fr.getHttpUrl());
            }
        }
        if(books.getId()==null){
            books.setCreateTime(new Date());
        }
        books.setChangeTime(new Date());
        books.setState(BookStateEnum.BOOK_STATE_ISSUE.getState());
        if(books.getIsdiscount()==null){
            books.setIsdiscount(1);
            books.setDiscount(0);
        }
        MallUser user = (MallUser) request.getSession().getAttribute(BookConstants.LOGIN_MALL_USER);
        books.setPublisher(user.getId());
        books.setPurchaser(0);
        if(books.getId()==null){
            if(baseMapper.insert(books)>0){
                return Result.createSuccess("发布成功");
            }
            return Result.createError("发布失败");
        }else{
            if(baseMapper.updateById(books)>0){
                return Result.createSuccess("更新成功");
            }
            return Result.createError("更新失败");
        }

    }

    @Override
    public Page<Books> booksList(BooksVo booksVo,HttpServletRequest request,String representative) {
        IPage<Books> page = new Page<>(booksVo.getPage(),booksVo.getLimit());
        QueryWrapper<Books> queryWrapper = new QueryWrapper<>();
        MallUser user = (MallUser) request.getSession().getAttribute(BookConstants.LOGIN_MALL_USER);
        queryWrapper.eq(user.getId()!=null,representative,user.getId());
        queryWrapper.orderByDesc("create_time");
        baseMapper.selectPage(page,queryWrapper);
        List<Books> records = page.getRecords();
        for (Books record : records) {
            if (record!=null){
                record.setPac(baseMapper.selectParentAndChildByBookClassify(record.getClassifyId()));
            }
        }
        page.setRecords(records);
        return (Page<Books>) page;
    }

    @Override
    public Result updateBookState(Books books) {
        if(books.getState()==1){
            books.setPurchaser(0);
        }
        if(baseMapper.updateById(books)>0){
            return  Result.createSuccess();
        }
        return  Result.createError();
    }

    @Override
    public Result booksListCount(HttpServletRequest request,String representative) {
        QueryWrapper<Books> queryWrapper = new QueryWrapper<>();
        MallUser user = (MallUser) request.getSession().getAttribute(BookConstants.LOGIN_MALL_USER);
        queryWrapper.eq(user.getId()!=null,representative,user.getId());
        Integer count = baseMapper.selectCount(queryWrapper);
        return Result.createSuccess(count,"有数据");
    }

    @Override
    public List<Books> alikeBook(String classifyId) {
        IPage<Books> page = new Page<>(1,5);
        QueryWrapper<Books> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(classifyId),"classify_id",classifyId);
        queryWrapper.eq("state",BookStateEnum.BOOK_STATE_ISSUE.getState());
        queryWrapper.orderByDesc("create_time");
        baseMapper.selectPage(page,queryWrapper);
        return page.getRecords();
    }

    @Override
    public Result booksListCount(Books books) {
        QueryWrapper<Books> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(books.getBookName()),"book_name",books.getBookName());
        queryWrapper.like(StringUtils.isNotBlank(books.getClassifyId()),"classify_id",books.getClassifyId());
        queryWrapper.eq("state",BookStateEnum.BOOK_STATE_ISSUE.getState());
        Integer integer = baseMapper.selectCount(queryWrapper);
        return Result.createSuccess(integer,"有数据");
    }

    @Override
    public List<Books> bookList(BooksVo booksVo) {
        IPage<Books> page = new Page<>(booksVo.getPage(),booksVo.getLimit());
        QueryWrapper<Books> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(booksVo.getBookName()),"book_name",booksVo.getBookName());
        if(StringUtils.isNotBlank(booksVo.getClassifyId())) {
            String[] split = booksVo.getClassifyId().split(",");
            for (String s : split) {
                queryWrapper.like( "classify_id", s);
            }
        }
        queryWrapper.eq("state",BookStateEnum.BOOK_STATE_ISSUE.getState());
        baseMapper.selectPage(page, queryWrapper);
        return page.getRecords();
    }

    @Override
    public List<Books> newBooks() {
        IPage<Books> page = new Page<>(1,BookConstants.NEW_BOOKS_LIMIT);
        QueryWrapper<Books> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("state",BookStateEnum.BOOK_STATE_ISSUE.getState());
        queryWrapper.orderByDesc("create_time");
        baseMapper.selectPage(page,queryWrapper);
        return page.getRecords();
    }

    @Override
    public List<Books> getBooksByClassifyID(Integer id) {
        IPage<Books> page = new Page<>(1,BookConstants.CLASSIFY_BOOKS_LIMIT);
        QueryWrapper<Books> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(id!=null,"classify_id",id);
        queryWrapper.eq("state",BookStateEnum.BOOK_STATE_ISSUE.getState());
        queryWrapper.orderByDesc("create_time");
        baseMapper.selectPage(page,queryWrapper);
        return page.getRecords();
    }
}
